<?php

namespace app\modules\v1\controllers;

use app\modules\v1\components\BaseController;
use common\models\db\CommercialLoanDetail;
use common\models\db\EqualResult;
use common\models\db\FundLoanDetail;
use common\models\db\LoanComparison;
use common\models\db\LoanRecord;
use common\models\db\PrincipalResult;
use Yii;

/**
 * 贷款对比相关接口
 */
class ComparisonController extends BaseController
{
    /**
     * 创建贷款对比 API
     * @return void
     */
    public function actionCreate()
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        $record1Id = intval($this->getPostData('record1Id', 0));
        $record2Id = intval($this->getPostData('record2Id', 0));
        
        if ($record1Id <= 0 || $record2Id <= 0) {
            $this->error('参数错误', 400);
        }
        
        // 查询两条记录
        $record1 = LoanRecord::findOne($record1Id);
        $record2 = LoanRecord::findOne($record2Id);
        
        if (!$record1 || $record1->user_id != $this->user->id) {
            $this->error('第一条记录不存在', 3001);
        }
        
        if (!$record2 || $record2->user_id != $this->user->id) {
            $this->error('第二条记录不存在', 3001);
        }
        
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        
        try {
            // 创建对比记录
            $comparison = new LoanComparison();
            $comparison->user_id = $this->user->id;
            $comparison->record1_id = $record1Id;
            $comparison->record2_id = $record2Id;
            $comparison->created_at = date('Y-m-d H:i:s', time());
            
            // 生成对比结论
            $conclusion = $this->generateConclusion($record1, $record2);
            $comparison->conclusion = $conclusion;
            
            if (!$comparison->save()) {
                throw new \Exception('保存对比记录失败');
            }
            
            $transaction->commit();
            
            $this->success(['comparisonId' => $comparison->id], '创建成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->error('创建对比记录失败: ' . $e->getMessage(), 4001);
        }
    }
    
    /**
     * 获取对比结果 API
     * @param int $comparisonId 对比记录ID
     * @return void
     */
    public function actionDetail($comparisonId)
    {
        if (!$this->user) {
            $this->error('用户未登录', 401);
        }
        
        // 查询对比记录
        $comparison = LoanComparison::findOne($comparisonId);
        
        if (!$comparison || $comparison->user_id != $this->user->id) {
            $this->error('对比记录不存在', 4002);
        }
        
        // 查询两条贷款记录
        $record1 = LoanRecord::findOne($comparison->record1_id);
        $record2 = LoanRecord::findOne($comparison->record2_id);
        
        if (!$record1 || !$record2) {
            $this->error('贷款记录不存在', 3001);
        }
        
        // 获取记录1的详情
        $record1Data = $this->getRecordDetail($record1);
        
        // 获取记录2的详情
        $record2Data = $this->getRecordDetail($record2);
        
        // 计算等额本息对比结果
        $equalCompare = [
            'monthlyPaymentDiff' => 0,
            'totalRepaymentDiff' => 0,
            'totalInterestDiff' => 0
        ];
        
        if (isset($record1Data['equalResult']) && isset($record2Data['equalResult'])) {
            $equalCompare = [
                'monthlyPaymentDiff' => round(abs($record1Data['equalResult']['monthlyPayment'] - $record2Data['equalResult']['monthlyPayment']), 2),
                'totalRepaymentDiff' => round(abs($record1Data['equalResult']['totalRepayment'] - $record2Data['equalResult']['totalRepayment']), 2),
                'totalInterestDiff' => round(abs($record1Data['equalResult']['totalInterest'] - $record2Data['equalResult']['totalInterest']), 2)
            ];
        }
        
        // 计算等额本金对比结果
        $principalCompare = [
            'firstMonthPaymentDiff' => 0,
            'decreasePerMonthDiff' => 0,
            'totalRepaymentDiff' => 0,
            'totalInterestDiff' => 0
        ];
        
        if (isset($record1Data['principalResult']) && isset($record2Data['principalResult'])) {
            $principalCompare = [
                'firstMonthPaymentDiff' => round(abs($record1Data['principalResult']['firstMonthPayment'] - $record2Data['principalResult']['firstMonthPayment']), 2),
                'decreasePerMonthDiff' => round(abs($record1Data['principalResult']['decreasePerMonth'] - $record2Data['principalResult']['decreasePerMonth']), 2),
                'totalRepaymentDiff' => round(abs($record1Data['principalResult']['totalRepayment'] - $record2Data['principalResult']['totalRepayment']), 2),
                'totalInterestDiff' => round(abs($record1Data['principalResult']['totalInterest'] - $record2Data['principalResult']['totalInterest']), 2)
            ];
        }
        
        $data = [
            'record1' => $record1Data,
            'record2' => $record2Data,
            'equalCompare' => $equalCompare,
            'principalCompare' => $principalCompare,
            'conclusion' => $comparison->conclusion
        ];
        
        $this->success($data, '获取成功');
    }
    
    /**
     * 获取记录详情
     * @param LoanRecord $record 贷款记录
     * @return array
     */
    private function getRecordDetail($record)
    {
        $data = [
            'loanType' => $record->loan_type,
            'repaymentType' => $record->repayment_type,
            'years' => $record->years,
            'totalAmount' => $record->total_amount
        ];
        
        // 获取贷款详情
        if ($record->loan_type == 'commercial') {
            $commercial = CommercialLoanDetail::findOne(['record_id' => $record->id]);
            if ($commercial) {
                $data['amount'] = $commercial->amount;
                $data['rate'] = $commercial->rate;
                $data['adjustedRate'] = $commercial->adjusted_rate;
            }
        } else if ($record->loan_type == 'fund') {
            $fund = FundLoanDetail::findOne(['record_id' => $record->id]);
            if ($fund) {
                $data['amount'] = $fund->amount;
                $data['rate'] = $fund->rate;
                $data['adjustedRate'] = $fund->rate;
            }
        } else if ($record->loan_type == 'combined') {
            $commercial = CommercialLoanDetail::findOne(['record_id' => $record->id]);
            $fund = FundLoanDetail::findOne(['record_id' => $record->id]);
            
            if ($commercial) {
                $data['commercialAmount'] = $commercial->amount;
                $data['commercialRate'] = $commercial->rate;
                $data['adjustedCommercialRate'] = $commercial->adjusted_rate;
            }
            
            if ($fund) {
                $data['fundAmount'] = $fund->amount;
                $data['fundRate'] = $fund->rate;
            }
        }
        
        // 获取等额本息结果
        $equal = EqualResult::findOne(['record_id' => $record->id]);
        if ($equal) {
            $data['equalResult'] = [
                'totalLoan' => $equal->total_loan,
                'totalRepayment' => $equal->total_repayment,
                'totalInterest' => $equal->total_interest,
                'monthlyPayment' => $equal->monthly_payment
            ];
        }
        
        // 获取等额本金结果
        $principal = PrincipalResult::findOne(['record_id' => $record->id]);
        if ($principal) {
            $data['principalResult'] = [
                'totalLoan' => $principal->total_loan,
                'totalRepayment' => $principal->total_repayment,
                'totalInterest' => $principal->total_interest,
                'firstMonthPayment' => $principal->first_month_payment,
                'decreasePerMonth' => $principal->decrease_per_month,
                'lastMonthPayment' => $principal->last_month_payment
            ];
        }
        
        return $data;
    }
    
    /**
     * 生成对比结论
     * @param LoanRecord $record1 贷款记录1
     * @param LoanRecord $record2 贷款记录2
     * @return string
     */
    private function generateConclusion($record1, $record2)
    {
        $conclusion = '';
        
        // 获取等额本息结果
        $equal1 = EqualResult::findOne(['record_id' => $record1->id]);
        $equal2 = EqualResult::findOne(['record_id' => $record2->id]);
        
        // 获取等额本金结果
        $principal1 = PrincipalResult::findOne(['record_id' => $record1->id]);
        $principal2 = PrincipalResult::findOne(['record_id' => $record2->id]);
        
        // 比较等额本息结果
        if ($equal1 && $equal2) {
            $monthlyPaymentDiff = abs($equal1->monthly_payment - $equal2->monthly_payment);
            $totalInterestDiff = abs($equal1->total_interest - $equal2->total_interest);
            
            $betterPlan = ($equal1->total_interest < $equal2->total_interest) ? '方案一' : '方案二';
            $worsePlan = ($equal1->total_interest < $equal2->total_interest) ? '方案二' : '方案一';
            
            $conclusion .= "在等额本息还款方式下，{$betterPlan}比{$worsePlan}少付利息" . round($totalInterestDiff, 2) . "元，月供也低" . round($monthlyPaymentDiff, 2) . "元。";
        }
        
        // 比较等额本金结果
        if ($principal1 && $principal2) {
            $firstMonthPaymentDiff = abs($principal1->first_month_payment - $principal2->first_month_payment);
            $totalInterestDiff = abs($principal1->total_interest - $principal2->total_interest);
            
            $betterPlan = ($principal1->total_interest < $principal2->total_interest) ? '方案一' : '方案二';
            $worsePlan = ($principal1->total_interest < $principal2->total_interest) ? '方案二' : '方案一';
            
            $conclusion .= "在等额本金还款方式下，{$betterPlan}比{$worsePlan}少付利息" . round($totalInterestDiff, 2) . "元，首月还款也低" . round($firstMonthPaymentDiff, 2) . "元。";
        }
        
        return $conclusion;
    }
} 